package com.qa.controller;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qa.pojo.DeptAndProInfo;
import com.qa.pojo.Users;
import com.qa.service.IUserService;

@Controller
@RequestMapping("/user")
public class UserController {
	@Resource
	private IUserService userService;
	Logger logger = Logger.getLogger(this.getClass());

	/**
	 * 根据用户名和密码判断需要跳转的页面 ---作废
	 * 
	 * @param login
	 * @param pass
	 * @param model
	 * @return
	 */
	@RequestMapping("/showUser")
	public String toIndex(String login, String pass, Model model) {

		System.out.println(login + "--" + pass);
		Users user = this.userService.getUserByNameAndPass(login, pass);
		if (user == null) {
			// model.addAttribute("index", "用户名或密码错误！");
			return "main";
		} else {
			// model.addAttribute("user", user);
			return "main";
		}
	}

	/**
	 * 获取部门、项目组信息
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 * @throws ServletException
	 */
	@RequestMapping("/getRegisterInfo")
	@ResponseBody
	public Map<String, Object> getRegisterInfo(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		response.setStatus(200);
		List<DeptAndProInfo> regisInfo = this.userService.getRegisterInfo();
		List<Map<String, Object>> listDept = new ArrayList<>();
		List<Map<String, Object>> listproject = new ArrayList<>();
		for (DeptAndProInfo dOrP : regisInfo) {
			Map<String, Object> map = new HashMap<>();
			map.put("id", dOrP.getTorpid());
			map.put("name", dOrP.getTorpname());
			if (dOrP.getTorp() == 1) {
				listDept.add(map);
			} else {
				listproject.add(map);
			}
		}
		resultMap.put("dept", listDept);
		resultMap.put("project", listproject);
		return resultMap;
	}

	/**
	 * 登录，通过用户名密码返回user对象，并存放在session里面
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 * @throws ServletException
	 */
	@RequestMapping("/login")
	@ResponseBody
	public Map<String, Object> toLogin(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		response.setStatus(200);
		String login = request.getParameter("login");// 通过参数名称接收从前台传来的数据
		String pass = request.getParameter("pass");
		if (login != null && pass != null) {
			try {
				login = URLDecoder.decode(login, "utf-8");
				pass = URLDecoder.decode(pass, "utf-8");
			} catch (Exception e) {
				e.printStackTrace();
				logger.error(e.getMessage());
			}
			Users user = this.userService.getUserByNameAndPass(login, pass);
			if (user == null) {
				resultMap.put("msg", "error");
			} else {
				resultMap.put("msg", "succes");
				request.getSession().setAttribute("user", user);
				request.getSession().setAttribute("sessionDate",
						System.currentTimeMillis());
				Cookie cookie1 = new Cookie("username", user.getUsername());
				response.addCookie(cookie1);
			}
		} else {
			resultMap.put("msg", "error");
		}
		return resultMap;
	}

	/**
	 * 登录到main页面
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/userMain", method = RequestMethod.GET)
	public String getAdminIndex(HttpServletRequest request,
			HttpServletResponse response) {
		/*
		 * ModelAndView view = new ModelAndView(); try { String path = ""; Users
		 * user = getUser(request); //view.addObject("user", user); path =
		 * "main"; view.setViewName(path); } catch (Exception e) {
		 * logger.error(e.getMessage()); }
		 */
		Cookie cookie1 = new Cookie("username", ((Users) request.getSession()
				.getAttribute("user")).getUsername());
		response.addCookie(cookie1);
		return "main";
	}

	/**
	 * 接口测试页面
	 * 
	 * @param session
	 *            Session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/interface")
	public String interface1(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Cookie cookie1 = new Cookie("username", ((Users) request.getSession()
				.getAttribute("user")).getUsername());
		response.addCookie(cookie1);
		return "interface1";
	}

	/**
	 * 接口测试Header設置頁面
	 * 
	 * @param session
	 *            Session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/interfaceHeader")
	public String interfaceHeader(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Cookie cookie1 = new Cookie("username", ((Users) request.getSession()
				.getAttribute("user")).getUsername());
		response.addCookie(cookie1);
		return "interfaceHeader";
	}
	
	
	/**
	 * 需求管理页面
	 * 
	 * @param session
	 *            Session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/demand")
	public String demand(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Cookie cookie1 = new Cookie("username", ((Users) request.getSession()
				.getAttribute("user")).getUsername());
		response.addCookie(cookie1);
		return "demand";
	}
	/**
	 * 用例库页面
	 * 
	 * @param session
	 *            Session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/testCase")
	public String testCase(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Cookie cookie1 = new Cookie("username", ((Users) request.getSession()
				.getAttribute("user")).getUsername());
		response.addCookie(cookie1);
		return "testCase";
	}

	/**
	 * 退出系统
	 * 
	 * @param session
	 *            Session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/logout")
	public String logout(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// 清除Session
		request.getSession().removeAttribute("user");
		request.getSession().removeAttribute("sessionDate");
		request.getSession().invalidate();
		return "index";
	}

	/**
	 * 工作日志
	 * 
	 * @param session
	 *            Session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/calendar")
	public String calendar(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Cookie cookie1 = new Cookie("username", ((Users) request.getSession()
				.getAttribute("user")).getUsername());
		response.addCookie(cookie1);
		return "page_calendar";
	}

	/**
	 * 注册
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 * @throws ServletException
	 */
	@RequestMapping(value = "/registerUser", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> registerUser(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		response.setStatus(200);

		Users user = new Users();
		int juese = Integer.valueOf(request.getParameter("juese"));

		int xiangmu = request.getParameter("xiangmu") == null ? -1 : Integer
				.valueOf(request.getParameter("xiangmu"));
		int bumen = request.getParameter("bumen") == null ? -1 : Integer
				.valueOf(request.getParameter("bumen"));
		String login = request.getParameter("login");// 通过参数名称接收从前台传来的数据
		String pass = request.getParameter("pass");
		String name = request.getParameter("name");
		if (login != null && pass != null && name != null) {
			try {
				login = URLDecoder.decode(login, "utf-8");
				pass = URLDecoder.decode(pass, "utf-8");
				name = URLDecoder.decode(name, "utf-8");
			} catch (Exception e) {
				e.printStackTrace();
				logger.error(e.getMessage());
			}
			user.setName(name);
			user.setPassword(pass);
			user.setUsername(login);
			int isSucess = this.userService.insertUsers(user, juese, bumen,
					xiangmu);
			if (isSucess == 0) {
				resultMap.put("msg", "error");
			} else {
				resultMap.put("msg", "succes");
				request.getSession().setAttribute("user", user);
				request.getSession().setAttribute("sessionDate",
						System.currentTimeMillis());
			}
			return resultMap;
		} else {
			return null;
		}

	}

	/**
	 * 跳转到周计划总结页面
	 * 
	 * @param session
	 *            Session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/weekplan")
	public String weekplan(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Cookie cookie1 = new Cookie("username", ((Users) request.getSession()
				.getAttribute("user")).getUsername());
		response.addCookie(cookie1);
		return "weekplan1";
	}

	/**
	 * 跳转到月计划总结页面
	 * 
	 * @param session
	 *            Session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/monthplan")
	public String monthplan(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Cookie cookie1 = new Cookie("username", ((Users) request.getSession()
				.getAttribute("user")).getUsername());
		response.addCookie(cookie1);
		return "monthplan";
	}
	
	/**
	 * 跳转到摄像头页面
	 * 
	 * @param session
	 *            Session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/pushControl")
	public String pushControl(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Cookie cookie1 = new Cookie("username", ((Users) request.getSession()
				.getAttribute("user")).getUsername());
		response.addCookie(cookie1);
		return "pushControl";
	}
	/**
	 * 跳转到注册页面
	 * 
	 * @param session
	 *            Session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/register")
	public String register(HttpSession session) throws Exception {
		return "register";
	}

	/**************
	 * 从session中得到用户
	 * 
	 * @param res
	 * @return
	 */
	public Users getUser(HttpServletRequest res) {
		Users user = (Users) res.getSession().getAttribute("user");
		return user;
	}
}